<script lang="ts" setup>

import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { TabPaneName } from 'element-plus'

const route = useRoute()
const router = useRouter()

let tabIndex = 1
const editableTabsValue = ref('1')
const editableTabs = ref([
    {
        title: 'ai1',
        name: '1',
        // content: 'Tab 1 content',
        path: '/N1/i1' // 添加路径关联
    },//留一个首页，设置不能关闭
])

// 根据当前路由更新或添加标签页
watch(() => route.path, (newPath) => {
    // 检查是否已存在该路径的标签页
    const existingTab = editableTabs.value.find(tab => tab.path === newPath)

    if (existingTab) {
        editableTabsValue.value = existingTab.name
    } else {
        // 从路由meta中获取标题
        const title = route.meta.title as string || 'New Tab'
        const newTabName = `${++tabIndex}`
        editableTabs.value.push({
            title: title,
            name: newTabName,
            // content: `${title} content`,
            path: newPath
        })

        editableTabsValue.value = newTabName
    }
}, { immediate: true })

const removeTab = (targetName: TabPaneName) => {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value

    if (activeName === targetName) {
        tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeName = nextTab.name
                    // 切换到下一个标签页时也跳转到对应的路由
                    router.push(nextTab.path)
                }
            }
        })
    }

    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
}

// 点击标签时跳转到对应路由
const handleTabClick = (tabName: TabPaneName) => {
    // console.log("click tab!", tabName);
    // console.log("当前editableTabs数据：", editableTabs.value);
    // 通过tab的值去找editableTabs里面name和tab相等的数组值，然后把它的path取出来
    const targetTab = editableTabs.value.find(tab => tab.name === tabName);
    // console.log("获取到被点击tab页的数组对象", targetTab);
    // 把当前路径切换为取出的路径
    if (targetTab) {
        // 只有当目标路径与当前路径不同时才跳转
        if (targetTab.path !== route.path) {
            router.push(targetTab.path);
        }
    } else {
        console.warn(`未找到名称 ${tabName} 对应的标签页`);
    }
}

// 添加点击事件
const handleCommand = (command: string | number | object) => {
  if (command === "closeAll") {
    // 关闭所有标签页，只保留首页
    editableTabs.value = editableTabs.value.filter(tab => tab.name === '1')
    editableTabsValue.value = '1'
    router.push(editableTabs.value[0].path) // 跳转到首页
  } else if (command === "closeLeft") {
    // 关闭当前标签左侧的所有标签页（不包括首页和当前标签）
    const currentIndex = editableTabs.value.findIndex(tab => tab.name === editableTabsValue.value)
    editableTabs.value = editableTabs.value.filter((tab, index) => 
      index >= currentIndex || tab.name === '1'
    )
  } else if (command === "closeRight") {
    // 关闭当前标签右侧的所有标签页
    const currentIndex = editableTabs.value.findIndex(tab => tab.name === editableTabsValue.value)
    editableTabs.value = editableTabs.value.filter((tab, index) => 
      index <= currentIndex || tab.name === '1'
    )
  } else if (command === "closeOther") {
    // 关闭除当前标签和首页外的所有标签页
    editableTabs.value = editableTabs.value.filter(tab => 
      tab.name === editableTabsValue.value || tab.name === '1'
    )
  }
  
  // 如果当前活动标签被关闭了（理论上不会发生，因为首页不能关闭），则跳转到首页
  if (!editableTabs.value.some(tab => tab.name === editableTabsValue.value)) {
    editableTabsValue.value = '1'
    router.push(editableTabs.value[0].path)
  }
}

</script>

<template>
    <div class="flex-box">
        <el-tabs v-model="editableTabsValue" type="card" class="demo-tabs" @tab-remove="removeTab"
            @tab-change="handleTabClick">
            <!-- 标签页内容 -->
            <el-tab-pane v-for="item in editableTabs" :key="item.name" :label="item.title" :name="item.name"
                :closable="item.name !== '1'"> <!-- 只有不是首页的标签才显示关闭按钮 -->
            </el-tab-pane>
        </el-tabs>
        <div>
            <el-dropdown placement="bottom-end" trigger="click"  @command="handleCommand">
                <el-button>
                    <el-icon class="arrowdown-icon">
                        <ArrowDown />
                    </el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="closeAll">
                            <el-icon><CircleClose /></el-icon>关闭全部
                        </el-dropdown-item>
                        <el-dropdown-item command="closeLeft">
                            <el-icon><ArrowLeft /></el-icon>关闭左侧
                        </el-dropdown-item>
                        <el-dropdown-item command="closeRight">
                            <el-icon><ArrowRight /></el-icon>关闭右侧
                        </el-dropdown-item>
                        <el-dropdown-item command="closeOther">
                            <el-icon><Close /></el-icon>关闭其他
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.flex-box {
    background-color: #fafbfc;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.demo-tabs {
    padding: 0 10px; // 添加左右内边距

    :deep(.el-tabs__header) {
        margin: 0;
        background-color: white; // 确保头部背景也是白色
        border-bottom: 1px solid #e6e6e6; // 添加底部边框线
    }

    :deep(.el-tabs__nav) {
        border: none;
    }

    :deep(.el-tabs__item) {
        height: 32px;
        line-height: 32px;
        padding: 0 15px;
        color: #333; // 设置标签文字颜色
        &.is-active {
            font-size: 18px;
            font-weight: bold;
            color: #409EFF; // 活动标签颜色
        }
    }

    :deep(.el-tabs__nav-next),
    :deep(.el-tabs__nav-prev) {
        line-height: 32px;
    }
}
</style>